<template>
  <div>
    <div style="width: 94%; margin: 0 auto;">
      <p>{{ $t("module.tenantManage.warning.tip") }}</p>
    </div>
    <Form :model="modelForm" ref="editForm" :rules="rule" :label-width="100" style="margin-top: 20px;">
      <Row :gutter="32" type="flex">
        <Col span="12">
          <Form-item :label="$t('module.tenantManage.tenantCode')">
            <Input v-model="tenantInfo.tenantCode"  disabled />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item :label="$t('module.tenantManage.tenantName')">
            <Input v-model="tenantInfo.tenantName"  disabled />
          </Form-item>
        </Col>
         <Col span="24">
          <!-- 用户中心 -->
          <Form-item prop="userCenter" :label="$t('module.tenantManage.userCenter')">
            <Input
              v-model.trim="modelForm.userCenter"
              :placeholder="`${$t('common.pleaseInput')}${$t('module.tenantManage.userCenter')}`"
              
            />
          </Form-item>
        </Col>
        <Col span="24">
          <!-- 组织中心 -->
          <Form-item prop="orgCenter" :label="$t('module.tenantManage.orgCenter')">
            <Input
              v-model.trim="modelForm.orgCenter"
              :placeholder="`${$t('common.pleaseInput')}${$t('module.tenantManage.orgCenter')}`"
              
            />
          </Form-item>
        </Col>
      </Row>
      <!-- <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="userCenter" :label="$t('module.tenantManage.userCenter')">
            <Input
              v-model.trim="modelForm.userCenter"
              :placeholder="`${$t('common.pleaseInput')}${$t('module.tenantManage.userCenter')}`"
              
            />
          </Form-item>
        </Col>
      </Row>
      <Row>
        <Col span="24">
          <Form-item prop="orgCenter" :label="$t('module.tenantManage.orgCenter')">
            <Input
              v-model.trim="modelForm.orgCenter"
              :placeholder="`${$t('common.pleaseInput')}${$t('module.tenantManage.orgCenter')}`"
              
            />
          </Form-item>
        </Col>
      </Row> -->
    </Form>
  </div>
</template>
<script>
import { getTenantConfigValue, addOrUpdateConfigValue } from "@/api/teantManageAPI.js";
import locales from "./locales.js";
export default {
  name: "TenantConfig",
  mixins: [locales],
  props: {
    tenantInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      userCenterId: "",
      orgCenterId: "",
      userConfigItemId: "",
      orgConfigItemId: "",
      defaultConfigUser: false,
      copyUserCenter: "",
      defaultConfigOrg: false,
      copyOrgCenter: "",
      isModifyUser: false,
      isModifyOrg: false,
      modelForm: {
        userCenter: "",
        orgCenter: "",
        userConfigInvalid: false,
        orgConfigInvalid: false
      },
      rule: {
        userCenter: [
          { required: true,message: `${this.$t('common.pleaseInput')}${this.$t('module.tenantManage.userCenter')}`, trigger: "blur" },
          {
            type: 'string',
            max: 1000,
            message: this.$t("common.warning.lengMaxFormat", ['1000'])
          }
        ],
        orgCenter: [
          { required: true, message: `${this.$t('common.pleaseInput')}${this.$t('module.tenantManage.orgCenter')}`, trigger: "blur" },
          {
            type: 'string',
            max: 1000,
            message: this.$t("common.warning.lengMaxFormat", ['1000'])
          },
        ]
      }
    };
  },
  computed: {
    actions() {
      return [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ];
    }
  },
  created: function () {
    this.init();
    this.$emit("SetTitle", this.$t("module.tenantManage.tenantConfig"));
    this.$emit("SetPageWidth", 600);
    this.$emit("SetPageMinHeight", 300);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    async init() {
      let USER = {
        tenantCode: this.tenantInfo.tenantCode,
        configCode: "SYS_USER_CENTER"
      };
      let ORG = {
        tenantCode: this.tenantInfo.tenantCode,
        configCode: "SYS_ORG_CENTER"
      };
      // 获取用户中心、获取组织中心
      const [{ data: userData }, { data: orgData }] = await Promise.all([
        getTenantConfigValue(USER),
        getTenantConfigValue(ORG)
      ]);
      let msg = "";
      // 使用平台配置 且 配置无效，给出提示
      if (!userData.id || (!!userData.defaultConfig && userData.enabled == 0)) {
        msg = this.$t(`module.tenantManage.warning.systemConfigInvalid`, ["SYS_USER_CENTER"]);
      } else {
        this.userConfigItemId = userData.configItemId;
        this.defaultConfigUser = userData.defaultConfig;
        this.modelForm.userCenter = userData.value;
        this.userCenterId = userData.id;
        this.copyUserCenter = JSON.parse(JSON.stringify(this.modelForm.userCenter));
        this.modelForm.userConfigInvalid = userData.hasInvalidConfig;
      }

      // 使用平台配置 且 配置无效，给出提示
      if (!orgData.id || (!!orgData.defaultConfig && orgData.enabled == 0)) {
        msg += this.$t(`module.tenantManage.warning.systemConfigInvalid`, ["SYS_ORG_CENTER"]);
      } else {
        this.orgConfigItemId = orgData.configItemId;
        this.defaultConfigOrg = orgData.defaultConfig;
        this.modelForm.orgCenter = orgData.value;
        this.orgCenterId = orgData.id;
        this.copyOrgCenter = JSON.parse(JSON.stringify(this.modelForm.orgCenter));
        this.modelForm.orgConfigInvalid = orgData.hasInvalidConfig;
      }
      // 消息合并提示
      if (msg) {
        this.$message.error({
          content: msg,
          duration: 3
        });
      }
    },
    save() {
      this.$refs["editForm"].validate(async valid => {
        if (valid) {
          if (
            this.defaultConfigUser != null &&
            this.defaultConfigOrg != null &&
            !this.isModifyOrg &&
            !this.isModifyUser
          ) {
            this.$message.success({
              content: this.$t("common.updateSuccess"),
              duration: 3
            });
            this.$emit("Close");
            return;
          }
          this.actions[0].loading = true;
          let userData = null;
          let orgData = null;
          let paramUser = {
            id: this.defaultConfigUser == null ? this.userCenterId : "",
            configItemId: this.userConfigItemId,
            value: this.modelForm.userCenter,
            hasInvalidConfig: this.modelForm.userConfigInvalid,
            description: "",
            enabled: 1,
            scopeContextName: this.tenantInfo.tenantCode,
            tenantCode: this.tenantInfo.tenantCode,
            itemCode: "SYS_USER_CENTER",
            scopeContext: null,
            scopeLevel: 1,
            valueSetItemId: null
          };
          // this.defaultConfigUser == null时使用upate接口
          let userOperation = null;
          if (this.defaultConfigUser == null) {
            userOperation = "update";
          } else if (this.isModifyUser) {
            // 如果this.defaultConfigUser == true并且修改了用户中心（this.isModifyUser = true）  使用add接口
            userOperation = "add";
          }
          if (userOperation != null) {
            userData = await addOrUpdateConfigValue(paramUser, userOperation);
          }

          let paramOrg = {
            id: this.defaultConfigOrg == null ? this.orgCenterId : "",
            configItemId: this.orgConfigItemId,
            value: this.modelForm.orgCenter,
            hasInvalidConfig: this.modelForm.orgConfigInvalid,
            description: "",
            enabled: 1,
            scopeContextName: this.tenantInfo.tenantCode,
            tenantCode: this.tenantInfo.tenantCode,
            itemCode: "SYS_ORG_CENTER",
            scopeContext: null,
            scopeLevel: 1,
            valueSetItemId: null
          };
          let orgOperation = null;
          // this.defaultConfigOrg == null时使用upate接口
          if (this.defaultConfigOrg == null) {
            orgOperation = "update";
          } else if (this.isModifyOrg) {
            // 如果this.defaultConfigOrg == true并且修改了组织中心（this.isModifyOrg = true）  使用add接口
            orgOperation = "add";
          }
          if (orgOperation != null) {
            orgData = await addOrUpdateConfigValue(paramOrg, orgOperation);
          }
          this.actions[0].loading = false;
          if (userData == null || userData == true || orgData == null || orgData == true) {
            this.$message.success({
              content: this.$t("common.updateSuccess"),
              duration: 3
            });
            this.$emit("Close", true);
          }
        } else {
          // 错误提示： 表单验证未通过，请修改
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
        }
      });
    }
  },
  watch: {
    // 监听修改后的用户中心是否默认用户中心一样
    "modelForm.userCenter": function (val) {
      if (val != this.copyUserCenter) {
        this.isModifyUser = true;
      } else {
        this.isModifyUser = false;
      }
    },
    // 监听修改后的组织中心是否默认组织中心一样
    "modelForm.orgCenter": function (val) {
      if (val != this.copyOrgCenter) {
        this.isModifyOrg = true;
      } else {
        this.isModifyOrg = false;
      }
    }
  },
  directives: {}
};
</script>

<style lang="less">
.useful-life-wrap {
  .ivu-date-picker {
    width: 100%;
  }
}
</style>
